<!DOCTYPE html>
<html lang="zh-CN">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>数据表格 - 扫码登录</title>
  <!-- <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet"> -->
  <style>
    body {
      font-family: 'Microsoft YaHei', sans-serif;
    }
    .login-container {
      max-width: 500px;
      margin: 50px auto;
      padding: 20px;
      border-radius: 10px;
      box-shadow: 0 5px 15px rgba(0, 0, 0, 0.1);
      text-align: center;
      position: relative;
    }
    .qrcode-container {
      margin: 20px auto;
      padding: 15px;
      border: 1px solid #eee;
      border-radius: 10px;
      display: inline-block;
    }
    .data-container {
      max-width: 800px;
      margin: 50px auto;
      padding: 20px;
      border-radius: 10px;
      box-shadow: 0 5px 15px rgba(0, 0, 0, 0.1);
      display: none;
    }
    .qrcode-img {
      max-width: 200px;
    }
    .qrcode-status-panel {
      margin: 15px 0;
      padding: 10px;
      border-radius: 8px;
      background: #f8f9fa;
    }
    .status-text {
      font-weight: bold;
      margin-bottom: 5px;
    }
    .qrcode-timer {
      font-size: 12px;
      color: #666;
    }
    .refresh-button {
      margin-top: 15px;
    }
    .status-pending {
      color: #6c757d;
    }
    .status-scanned {
      color: #ffc107;
    }
    .status-confirmed {
      color: #28a745;
    }
    .status-expired {
      color: #dc3545;
    }
    
    /* 扫码日志区域样式 */
    .scan-log-panel {
      margin-top: 30px;
      text-align: left;
      background-color: #f8f9fa;
      border-radius: 10px;
      padding: 15px;
      font-size: 14px;
      height: 200px;
      overflow-y: auto;
      display: none; /* 默认隐藏，只有扫码后才显示 */
    }
    .scan-log-title {
      font-weight: bold;
      margin-bottom: 10px;
      color: #1890ff;
    }
    .log-entry {
      padding: 8px;
      border-bottom: 1px solid #eee;
    }
    .log-entry:last-child {
      border-bottom: none;
    }
    .log-time {
      color: #666;
      font-size: 12px;
    }
    .log-message {
      margin: 5px 0;
      word-break: break-all;
    }
    .log-data {
      background-color: #f0f0f0;
      padding: 5px;
      border-radius: 5px;
      font-family: monospace;
      font-size: 12px;
      overflow-x: auto;
      white-space: pre-wrap;
    }
    
    /* 二维码信息面板样式 */
    .qrcode-info-panel {
      position: absolute;
      top: 0;
      right: -320px;
      width: 300px;
      background: #fffbe6;
      border: 1px solid #ffe58f;
      border-radius: 10px;
      padding: 15px;
      font-size: 14px;
      box-shadow: 0 2px 8px rgba(0,0,0,0.08);
      text-align: left;
    }
    .qrcode-info-title {
      font-weight: bold;
      color: #faad14;
      margin-bottom: 10px;
      font-size: 16px;
    }
    .qrcode-info-item {
      margin-bottom: 8px;
      word-break: break-all;
    }
    .qrcode-info-label {
      color: #666;
      margin-bottom: 4px;
    }
    .qrcode-info-value {
      background: #fff;
      padding: 8px;
      border-radius: 4px;
      border: 1px solid #f0f0f0;
      font-family: monospace;
    }
    @media (max-width: 900px) {
      .qrcode-info-panel {
        position: static;
        width: 100%;
        margin-top: 20px;
        right: 0;
      }
    }
    .qrcode-mask {
      position: absolute;
      left: 0;
      top: 0;
      width: 100%;
      height: 100%;
      background: rgba(0,0,0,0.35);
      z-index: 10;
      display: flex;
      align-items: center;
      justify-content: center;
      color: #fff;
      font-size: 20px;
      border-radius: 10px;
      pointer-events: all;
    }
    .qrcode-scanned-tip {
      color: #fff;
      background: #ff4d4f;
      padding: 8px 20px;
      border-radius: 8px;
      font-size: 18px;
      margin-bottom: 10px;
      display: inline-block;
      font-weight: bold;
    }
  </style>
</head>
<body>
  <div class="container">
    <!-- 登录区域 -->
    <div id="loginContainer" class="login-container">
      <h2>数据表格扫码登录</h2>
      <p>请使用微信小程序扫描下方二维码登录</p>
      
      <div style="display: flex; justify-content: center; align-items: flex-start; position: relative;">
        <div class="qrcode-container" style="position:relative;">
          <div id="qrcodeScannedTip" class="qrcode-scanned-tip" style="display:none;position:absolute;top:-40px;left:50%;transform:translateX(-50%);"></div>
          <div id="qrcodeImage"></div>
          <div id="qrcodeMask" class="qrcode-mask" style="display:none;">扫码成功，请在手机上授权登录</div>
          <div class="qrcode-status-panel">
            <div id="statusText" class="status-text status-pending">等待扫码...</div>
            <div id="qrcodeTimer" class="qrcode-timer">有效期：5:00</div>
          </div>
        </div>

        <!-- 二维码信息面板 -->
        <div id="qrcodeInfoPanel" class="qrcode-info-panel">
          <div class="qrcode-info-title">二维码信息</div>
          <div class="qrcode-info-item">
            <div class="qrcode-info-label">二维码ID</div>
            <div id="qrcodeId" class="qrcode-info-value">-</div>
          </div>
          <div class="qrcode-info-item">
            <div class="qrcode-info-label">创建时间</div>
            <div id="qrcodeCreateTime" class="qrcode-info-value">-</div>
          </div>
          <div class="qrcode-info-item">
            <div class="qrcode-info-label">当前状态</div>
            <div id="qrcodeCurrentStatus" class="qrcode-info-value">-</div>
          </div>
        </div>
      </div>
      
      <button id="refreshQrcode" class="btn btn-primary refresh-button">刷新二维码</button>
      
      <!-- 扫码日志区域 -->
      <div id="scanLogPanel" class="scan-log-panel">
        <div class="scan-log-title">扫码交互日志</div>
        <div id="scanLogContent"></div>
      </div>
    </div>
    
    <!-- 数据表格区域 -->
    <div id="dataContainer" class="data-container">
      <h2>数据表格</h2>
      <div class="text-end mb-3">
        <button id="logoutButton" class="btn btn-outline-danger">退出登录</button>
      </div>
      
      <div class="table-responsive">
        <table class="table table-striped table-hover">
          <thead>
            <tr>
              <th>项目名称</th>
              <th>数值</th>
              <th>日期</th>
            </tr>
          </thead>
          <tbody id="dataTableBody">
            <!-- 数据将动态加载到这里 -->
          </tbody>
        </table>
      </div>
    </div>
  </div>

  <!-- <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script> -->
  <script>
    document.addEventListener('DOMContentLoaded', () => {
      // DOM元素
      const loginContainer = document.getElementById('loginContainer');
      const dataContainer = document.getElementById('dataContainer');
      const qrcodeImage = document.getElementById('qrcodeImage');
      const statusText = document.getElementById('statusText');
      const qrcodeTimer = document.getElementById('qrcodeTimer');
      const refreshQrcodeButton = document.getElementById('refreshQrcode');
      const dataTableBody = document.getElementById('dataTableBody');
      const logoutButton = document.getElementById('logoutButton');
      const scanLogPanel = document.getElementById('scanLogPanel');
      const scanLogContent = document.getElementById('scanLogContent');
      
      // 新增：二维码信息面板相关元素
      const qrcodeInfoPanel = document.getElementById('qrcodeInfoPanel');
      const qrcodeIdElement = document.getElementById('qrcodeId');
      const qrcodeCreateTimeElement = document.getElementById('qrcodeCreateTime');
      const qrcodeCurrentStatusElement = document.getElementById('qrcodeCurrentStatus');
      
      // 状态变量
      let currentQrcodeId = null;
      let qrcodeCreatedTime = null;
      let pollingIntervalId = null;
      let countdownIntervalId = null;
      
      // 添加扫码日志
      function addScanLog(message, data = null) {
        // 确保日志面板显示
        scanLogPanel.style.display = 'block';
        
        const entry = document.createElement('div');
        entry.className = 'log-entry';
        
        const time = document.createElement('div');
        time.className = 'log-time';
        time.textContent = new Date().toLocaleTimeString();
        
        const msg = document.createElement('div');
        msg.className = 'log-message';
        msg.textContent = message;
        
        entry.appendChild(time);
        entry.appendChild(msg);
        
        if (data) {
          const dataEl = document.createElement('pre');
          dataEl.className = 'log-data';
          dataEl.textContent = typeof data === 'string' ? data : JSON.stringify(data, null, 2);
          entry.appendChild(dataEl);
        }
        
        scanLogContent.appendChild(entry);
        // 自动滚动到底部
        scanLogContent.scrollTop = scanLogContent.scrollHeight;
      }
      
      // 检查是否已登录
      checkLoginStatus();
      
      // 刷新二维码按钮点击事件
      refreshQrcodeButton.addEventListener('click', () => {
        generateQrCode();
      });
      
      // 退出登录按钮点击事件
      logoutButton.addEventListener('click', () => {
        logout();
      });
      
      // 生成新二维码
      function generateQrCode() {
        clearAllTimers();
        window._scannedToastShown = false;
        scanLogPanel.style.display = 'none';
        scanLogContent.innerHTML = '';
        
        statusText.textContent = '加载中...';
        statusText.className = 'status-text status-pending';
        qrcodeTimer.textContent = '';
        
        // 重置二维码信息
        updateQrcodeInfo('-', 'loading');
        
        fetch('/api/qrcode')
          .then(response => response.json())
          .then(data => {
            currentQrcodeId = data.qrcodeId;
            qrcodeCreatedTime = new Date();
            
            qrcodeImage.innerHTML = `<img src="${data.qrcodeImage}" class="qrcode-img" alt="扫码登录">`;
            statusText.textContent = '等待扫码...';
            statusText.className = 'status-text status-pending';
            
            // 更新二维码信息
            updateQrcodeInfo(data.qrcodeId, 'pending');
            
            startPollingStatus(data.qrcodeId);
            startCountdown();
          })
          .catch(error => {
            console.error('获取二维码失败:', error);
            statusText.textContent = '获取二维码失败，请重试';
            statusText.className = 'status-text status-expired';
            qrcodeTimer.textContent = '';
            updateQrcodeInfo('-', 'error');
          });
      }
      
      // 定期查询二维码状态
      function startPollingStatus(qrcodeId) {
        if (pollingIntervalId) {
          clearInterval(pollingIntervalId);
        }
        
        // 立即执行一次
        pollQrcodeStatus(qrcodeId);
        
        // 设置定期轮询
        pollingIntervalId = setInterval(() => {
          pollQrcodeStatus(qrcodeId);
        }, 2000); // 每2秒查询一次
      }
      
      // 查询二维码状态
      function pollQrcodeStatus(qrcodeId) {
        if (qrcodeId !== currentQrcodeId) {
          if (pollingIntervalId) {
            clearInterval(pollingIntervalId);
            pollingIntervalId = null;
          }
          return;
        }
        
        fetch(`/api/qrcode/${qrcodeId}/status`)
          .then(response => {
            if (!response.ok) {
              if (response.status === 400) {
                return response.json().then(data => {
                  throw new Error(data.error || '二维码已过期');
                });
              } else if (response.status === 404) {
                throw new Error('二维码不存在或已过期');
              } else {
                throw new Error(`HTTP error ${response.status}`);
              }
            }
            return response.json();
          })
          .then(data => {
            // 更新状态显示
            updateQrcodeStatus(data.status);
            
            // 如果已确认登录，停止轮询
            if (data.status === 'confirmed') {
              clearInterval(pollingIntervalId);
              pollingIntervalId = null;
            }
          })
          .catch(error => {
            console.error('轮询状态错误:', error);
            
            // 如果是过期错误，显示过期状态
            if (error.message.includes('过期')) {
              handleQrcodeExpired();
            }
          });
      }
      
      // 更新二维码状态显示
      function updateQrcodeStatus(status) {
        if (status === 'scanned') {
          statusText.textContent = '已扫码，请在手机上授权登录';
          statusText.className = 'status-text status-scanned';
          updateQrcodeInfo(currentQrcodeId, 'scanned');
          addScanLog('用户已扫描二维码，等待授权确认');
          // 新增：二维码上方红色提示和遮罩
          document.getElementById('qrcodeScannedTip').style.display = 'block';
          document.getElementById('qrcodeScannedTip').textContent = '扫码成功，请在手机上授权登录';
          document.getElementById('qrcodeMask').style.display = 'flex';
          if (!window._scannedToastShown) {
            window._scannedToastShown = true;
            showH5Toast('请在手机上授权登录');
          }
        } else {
          // 其它状态隐藏提示和遮罩
          document.getElementById('qrcodeScannedTip').style.display = 'none';
          document.getElementById('qrcodeMask').style.display = 'none';
        }
        if (status === 'confirmed') {
          statusText.textContent = '登录成功，正在跳转...';
          statusText.className = 'status-text status-confirmed';
          updateQrcodeInfo(currentQrcodeId, 'confirmed');
          addScanLog('用户已确认授权，登录成功');
          showH5Toast('登录成功');
          if (countdownIntervalId) {
            clearInterval(countdownIntervalId);
            countdownIntervalId = null;
          }
          fetchLoginConfirmation(currentQrcodeId);
        }
      }
      
      // 处理二维码过期
      function handleQrcodeExpired() {
        clearAllTimers();
        
        statusText.textContent = '二维码已过期，请刷新';
        statusText.className = 'status-text status-expired';
        qrcodeTimer.textContent = '已过期';
        
        updateQrcodeInfo(currentQrcodeId, 'expired');
        addScanLog('二维码已过期，请点击刷新按钮重新获取');
      }
      
      // 开始倒计时
      function startCountdown() {
        if (countdownIntervalId) {
          clearInterval(countdownIntervalId);
        }
        
        // 设置初始时间为5分钟
        let remainingSeconds = 5 * 60;
        updateCountdownDisplay(remainingSeconds);
        
        countdownIntervalId = setInterval(() => {
          remainingSeconds--;
          
          if (remainingSeconds <= 0) {
            clearInterval(countdownIntervalId);
            countdownIntervalId = null;
            handleQrcodeExpired();
            return;
          }
          
          updateCountdownDisplay(remainingSeconds);
        }, 1000);
      }
      
      // 更新倒计时显示
      function updateCountdownDisplay(seconds) {
        const minutes = Math.floor(seconds / 60);
        const secs = seconds % 60;
        qrcodeTimer.textContent = `有效期：${minutes}:${secs.toString().padStart(2, '0')}`;
      }
      
      // 获取登录确认信息
      function fetchLoginConfirmation(qrcodeId) {
        fetch(`/api/qrcode/${qrcodeId}/status`)
          .then(response => {
            if (!response.ok) {
              throw new Error(`HTTP error ${response.status}`);
            }
            return response.json();
          })
          .then(data => {
            if (data.status === 'confirmed') {
              const randomToken = 'tk_' + Math.random().toString(36).substring(2, 10);
              const randomOpenid = 'op_' + Math.random().toString(36).substring(2, 10);
              
              // 保存登录状态
              localStorage.setItem('token', randomToken);
              localStorage.setItem('openid', randomOpenid);
              
              // 添加扫码日志
              addScanLog('获取登录凭证成功，即将跳转到数据页面', {
                token: randomToken.substring(0, 8) + '...',
                openid: randomOpenid
              });
              
              // 延迟后显示数据页面
              setTimeout(() => {
                showDataTable();
              }, 1000);
            }
          })
          .catch(error => {
            console.error('获取登录确认失败:', error);
            addScanLog('获取登录确认失败', { error: error.message });
          });
      }
      
      // 清除所有计时器
      function clearAllTimers() {
        if (pollingIntervalId) {
          clearInterval(pollingIntervalId);
          pollingIntervalId = null;
        }
        
        if (countdownIntervalId) {
          clearInterval(countdownIntervalId);
          countdownIntervalId = null;
        }
      }
      
      // 检查登录状态
      function checkLoginStatus() {
        const token = localStorage.getItem('token');
        const openid = localStorage.getItem('openid');
        
        if (token && openid) {
          showDataTable();
        } else {
          generateQrCode();
        }
      }
      
      // 显示数据表格
      function showDataTable() {
        // 隐藏登录容器，显示数据容器
        loginContainer.style.display = 'none';
        dataContainer.style.display = 'block';
        
        // 加载数据
        loadData();
      }
      
      // 加载数据
      function loadData() {
        fetch('/api/data')
          .then(response => response.json())
          .then(data => {
            // 清空表格
            dataTableBody.innerHTML = '';
            
            // 填充数据
            data.forEach(item => {
              const row = document.createElement('tr');
              
              // 格式化日期
              const date = new Date(item.date);
              const formattedDate = `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}-${String(date.getDate()).padStart(2, '0')}`;
              
              row.innerHTML = `
                <td>${item.name}</td>
                <td>${item.value}</td>
                <td>${formattedDate}</td>
              `;
              
              dataTableBody.appendChild(row);
            });
          })
          .catch(error => {
            console.error('获取数据失败:', error);
            dataTableBody.innerHTML = '<tr><td colspan="3" class="text-center text-danger">获取数据失败，请刷新页面重试</td></tr>';
          });
      }
      
      // 退出登录
      function logout() {
        localStorage.removeItem('token');
        localStorage.removeItem('openid');
        
        // 隐藏数据容器，显示登录容器
        dataContainer.style.display = 'none';
        loginContainer.style.display = 'block';
        
        // 生成新的二维码
        generateQrCode();
      }
      
      // H5弹窗提示函数
      function showH5Toast(msg) {
        const toast = document.createElement('div');
        toast.textContent = msg;
        toast.style.position = 'fixed';
        toast.style.top = '30%';
        toast.style.left = '50%';
        toast.style.transform = 'translate(-50%, -50%)';
        toast.style.background = 'rgba(0,0,0,0.8)';
        toast.style.color = '#fff';
        toast.style.padding = '16px 32px';
        toast.style.borderRadius = '8px';
        toast.style.zIndex = 9999;
        document.body.appendChild(toast);
        setTimeout(() => {
          document.body.removeChild(toast);
        }, 2000);
      }
      
      // 更新二维码信息面板
      function updateQrcodeInfo(qrcodeId, status) {
        qrcodeIdElement.textContent = qrcodeId || '-';
        if (qrcodeCreatedTime) {
          qrcodeCreateTimeElement.textContent = qrcodeCreatedTime.toLocaleString();
        }
        
        let statusText = '-';
        switch(status) {
          case 'pending':
            statusText = '等待扫码';
            break;
          case 'scanned':
            statusText = '已扫码，等待确认';
            break;
          case 'confirmed':
            statusText = '已确认登录';
            break;
          case 'expired':
            statusText = '已过期';
            break;
          default:
            statusText = status || '-';
        }
        qrcodeCurrentStatusElement.textContent = statusText;
      }
    });
  </script>
</body>
</html> 